﻿using System;
using MySql.Simple.Mapper.Finders;
using MySql.Simple.Mapper.Structures;

namespace MySql.Simple.Mapper.Commands.Rows
{
    /// <summary>
    /// Reads the contents of a SQL table row into a given object type.
    /// </summary>
    public static class DeleteCommand
    {
        private const string Sql = @"DELETE FROM `{0}` WHERE `{1}` = {2};";

        /// <summary>
        /// Reads the contents of a SQL table row into a given object type.
        /// </summary>
        /// <returns></returns>
        public static void Execute<T>(object id, Connection connection)
        {
            // Get SQL ingredients
            var tableName = TableNameFinder.Find(typeof(T));

            // Get Columns
            var columns = ColumnFinder.Find(typeof(T));

            // ensure PK is set
            if (columns.HasPrimaryKey)
                throw new ApplicationException("Primary key has not been set on " + typeof(T).Name);

            connection.ExecuteNonQuery(Sql, null, tableName, columns.PrimaryKeyName, id.ToString());
        }

    }
}